import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
    //为请求头,添加Token验证的
    // if (store.getters.token) {
    config.headers['userId'] = getToken() //|| store.state.user.token
    // }
    return config
  },
  error => {
    // do something with request error
    console.log('请求拦截器失败', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
    const res = response.data
    // if (res.code !== '0000') {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   console.log('方法对付',res.msg)
    //   return Promise.reject(new Error(res.msg))
    // } else {
      return res
    // }
  },error => {
  console.log('err' + error) // for debug
  if (error.response && error.response.status === 401) {
      removeToken()
      router.push('/login')
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)


// 请求方法封装，拷贝直接用
export default {
  Get(url, data = {}) {
    return service({
      url: url,
      method: 'get',
      params: data
    })
  },

  Post(url, data = {}) {
    return service({
      url: url,
      method: 'post',
      data: data
    })
  },

  Put(url, data = {}) {
    return service({
      url: url,
      method: 'put',
      data: data
    })
  },

  Delete(url, data = {}) {
    return service({
      url: url,
      method: 'delete',
      data: data
    })
  },
  // 文件流
  filePost(url, data = {}) {
    return service({
      url: url,
      method: 'post',
      responseType: 'blob',
      data: data
    })
  },
}
